import {ScrollView, View, Text, Image} from '@tarojs/components';
import React, {Component} from 'react';
import {AtIcon, AtModal, AtModalHeader, AtModalContent, AtModalAction} from 'taro-ui';
import 'taro-ui/dist/style/components/modal.scss';
import Taro, {getCurrentInstance} from '@tarojs/taro';
import {connect} from 'react-redux';
import './index.less';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';
import defaultAvatar from '@/assets/image/customer/user-center/default.png';
import ryutil from '../../../libs/ryutil';
import bg from '@/assets/image/daoway/bg.png';
import btn from '@/assets/image/daoway/btn.png';
import {ant} from 'wmkit';

actions().actions.loadReducer();
// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class Index extends Component<Partial<T.IProps>, any> {
  constructor(props) {
    super(props);
    this.state = {
      channel: 'rykj',
      secret: '9a5cf90547b3475b961f6f136f97659e',
      daowayUrl: '',
    };
  }

  componentDidMount() {
    this.props.actions.init();
  }

  componentDidShow() {}

  componentWillUnmount() {
    this.props.actions.clean();
  }

  async itemClick(item) {
    let {
      main: {isAquamarineMember, isCrystalMember},
      actions: {action},
    } = this.props;

    // isAquamarineMember && isCrystalMember; //双会员
    // isAquamarineMember && !isCrystalMember; //蓝晶会员
    // !isAquamarineMember && isCrystalMember; //赤晶会员
    // !isAquamarineMember && !isCrystalMember; //普通用户

    if (!isAquamarineMember && !isCrystalMember) {
      action.commonChange('main.showModel', true);
    } else {
      // skipWay:0内部，1外部
      if (item.skipWay == 0) {
        Taro.navigateTo({
          url: item.url,
        });
      } else {
        if (item.outSkipWay == 0) {
          // H5跳转
          let {channel, secret} = this.state;
          let userInfos = Taro.getStorageSync('b2b-wechat@login').user || {};
          let phone = userInfos.phone;
          const param = `channel=${channel}&phone=${phone}&secret=${secret}`;
          let sign = ryutil.encrypt(param);
          const newUrl = `${item.url}&channel=${channel}&phone=${phone}&sign=${sign}&nav=0&top=1&banner=0`;
          this.setState({
            daowayUrl: newUrl,
          });
          // Taro.setStorageSync('url', newUrl);
          // Taro.navigateTo({
          //   url: '/pages/package-A/webview/index',
          // });
        } else if (item.outSkipWay == 1) {
          // 小程序跳转
          if (item.miniProgramPath == 'wxde8ac0a21135c07d') {
            //美团
            if (item.url.indexOf('-') != -1) {
              let arr = item.url.split('-');
              Taro.navigateTo({
                url: `/pages/package-D/meituan/index?cat0Id=${arr[0]}&cat1Id=${arr[1]}&title=${item.twoName}`,
              });
            } else {
              Taro.showToast({
                title: '菜单配置错误，请联系管理员',
                icon: 'none',
                duration: 2000,
              });
            }
          } else if (item.miniProgramPath == 'wxf772255062165d94') {
            Taro.navigateToMiniProgram({
              appId: item.miniProgramPath,
              path: item.url,
              //develop开发版；trial体验版；release正式版
              envVersion: 'release',
              success(res) {
                // 打开成功
              },
              fail(err) {},
            });
          }
        } else if (item.outSkipWay == 2) {
          // 插件跳转
          let {customerId} = this.props.main;
          let query = {
            movieuid: customerId,
            movieapikey: await ant.getAntApiKey(),
            index: '/pages/index/index',
          };
          let kvarr = [];
          for (const key in query) {
            if (Object.prototype.hasOwnProperty.call(query, key)) {
              const e = query[key];
              kvarr.push(`${key}=${e}`);
            }
          }
          let url = `plugin://${item.pluginName}/index?${kvarr.join('&')}`;
          Taro.navigateTo({
            url,
          });
        }
      }
    }
  }

  render() {
    let {daowayUrl} = this.state;
    let {
      main: {showModel, list},
      actions: {action},
    } = this.props;
    return (
      <View className="packageDCommunityService">
        <ScrollView className="scrollView" scrollY>
          <View>
            {list.map((item, index) => (
              <>
                <Text className="title">{item.oneName}</Text>
                <View className="listBox">
                  {item?.twoCategoryVOList &&
                    item?.twoCategoryVOList.length > 0 &&
                    item?.twoCategoryVOList.map((v, k) => (
                      <View
                        className="item"
                        onClick={(e) => {
                          e.stopPropagation();
                          this.itemClick(v);
                        }}
                      >
                        {v?.twoImageSign && <Image className="icon" src={v?.twoImageSign} mode="aspectFill" />}
                        <Text className="name">{v?.twoName}</Text>
                      </View>
                    ))}
                </View>
              </>
            ))}
          </View>
          <AtModal
            isOpened={showModel}
            cancelText="取消"
            confirmText="开通"
            onClose={() => {
              action.commonChange('main.showModel', false);
            }}
            onCancel={() => {
              action.commonChange('main.showModel', false);
            }}
            onConfirm={() => {
              action.commonChange('main.showModel', false);
              Taro.navigateTo({url: '/pages/package-A/memberOpen/index'});
            }}
            content="您不是会员，无法使用该服务，需开通会员！"
          />
        </ScrollView>
        {daowayUrl && (
          <View className="tipBox">
            <View className="tipBox-con">
              <Image className="tipBox-con-bg" src={bg} mode="aspectFit" />
              <Image
                className="tipBox-con-btn"
                src={btn}
                mode="aspectFit"
                onClick={() => {
                  Taro.setClipboardData({
                    //设置系统剪贴板的内容
                    data: daowayUrl,
                    success(res) {
                      // Taro.getClipboardData({ // 获取系统剪贴板的内容
                      //   success(res) {
                      Taro.showToast({
                        title: '内容已复制',
                      });
                      //   }
                      // })
                    },
                  });
                }}
              />
              <View
                className="tipBox-con-cancel"
                onClick={() => {
                  this.setState({
                    daowayUrl: '',
                  });
                }}
              >
                取消
              </View>
            </View>
          </View>
        )}
      </View>
    );
  }
}
